package com.esd.device.task;

import com.esd.common.utils.SpringUtils;
import com.esd.device.entity.DeviceChannel;
import com.esd.device.entity.EsdLog;
import com.esd.device.entity.vo.DeviceVo;
import com.esd.device.entity.vo.DustStatusVo;
import com.esd.device.entity.vo.PositionStoreVo;
import com.esd.device.service.DeviceChannelService;
import com.esd.device.service.DeviceService;
import com.esd.device.service.EsdLogService;
import com.esd.device.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@DisallowConcurrentExecution // 禁止任务并发运行
public class LogJob extends QuartzJobBean {
    private final static Tcp_Utils_Nio tcp_utils = SpringUtils.getBean(Tcp_Utils_Nio.class) ;
    private final static DeviceService deviceService = SpringUtils.getBean(DeviceService.class) ;
    private final static DeviceChannelService deviceChannelService = SpringUtils.getBean(DeviceChannelService.class) ;
    private final static EsdLogService esdLogService = SpringUtils.getBean(EsdLogService.class) ;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String serverIp = jobDataMap.getString("serverIp");
        List<DeviceVo> deviceVos = deviceService.selectVosByServerIp(serverIp);
        if (deviceVos != null && !deviceVos.isEmpty()) {
            for (DeviceVo deviceVo : deviceVos) {
                if (deviceVo.getDeviceTypeName().equals("尘埃粒子计数器")){
                    String stationId = deviceVo.getStationId();
                    String command = NumberUtils.longToHexString(Long.parseLong(stationId) , 2) + " 03 00 00 00 1A";
                    String command2 = NumberUtils.longToHexString(Long.parseLong(stationId) , 2) + " 03 00 70 00 0C";
                    ReentrantLock reentrantLock = DeviceConstants.LockMap.get(deviceVo.getServerIp());
                    reentrantLock.lock();
                    String tcpResult = null ;
                    String tcpResult2 = null ;
                    try {
                        tcpResult = tcp_utils.sendCommand2(deviceVo.getServerIp() , deviceVo.getServerPort() , command , 500) ;
                    } catch (Exception e) {
                        log.error("加锁失败！！ {}" , e.getMessage() );
                    } finally {
                        reentrantLock.unlock();
                    }
                    try {
                        TimeUnit.MILLISECONDS.sleep(20);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    reentrantLock.lock();
                    try {
                        tcpResult2 = tcp_utils.sendCommand2(deviceVo.getServerIp() , deviceVo.getServerPort() , command2 , 500) ;
                    } catch (Exception e) {
                        log.error("加锁失败！！ {}" , e.getMessage() );
                    } finally {
                        reentrantLock.unlock();
                    }
                    if (tcpResult != null && tcpResult2 != null) {
                        List<DeviceChannel> deviceChannels = deviceChannelService.getListByDeviceId(deviceVo.getDeviceId());
                        if (tcpResult.equals("error") || tcpResult2.equals("error") || tcpResult.isEmpty() || tcpResult2.isEmpty()) {
                            if(tcpResult.equals("error") || tcpResult2.equals("error") ) {
                                if(DeviceConstants.GatewayMissTimesMap.containsKey(deviceVo.getServerIp())){
                                    Integer timeoutTime = DeviceConstants.GatewayMissTimesMap.get(deviceVo.getServerIp());
                                    if (timeoutTime != null && timeoutTime < 10){
                                        DeviceConstants.GatewayMissTimesMap.put(
                                                deviceVo.getServerIp() ,
                                                DeviceConstants.GatewayMissTimesMap.get(deviceVo.getServerIp()) + 1
                                        );
                                    }
                                }else {
                                    DeviceConstants.GatewayMissTimesMap.put(deviceVo.getServerIp() , 1);
                                }
                            }else {
                                DeviceConstants.GatewayMissTimesMap.put(deviceVo.getServerIp() , 0);
                            }
                            PositionStoreVo positionStoreVo =
                                    DeviceConstants.ChannelStatusMap.get(deviceVo.getStationId() + "_1");
                            if (positionStoreVo == null) {
                                positionStoreVo = new PositionStoreVo() ;
                            }
                            positionStoreVo.setId(deviceVo.getStationId() + "_1");
                            positionStoreVo.setStatus("失联");
                            positionStoreVo.setDetail("失联");
                            positionStoreVo.setChannelTypeName(deviceChannels.get(0).getChannelType());
                            DeviceConstants.ChannelStatusMap.put(
                                    deviceVo.getStationId() + "_1",
                                    positionStoreVo);
                            DustStatusVo dustStatusVo = new DustStatusVo() ;
                            dustStatusVo.setPosition(deviceVo.getPosition());
                            DeviceConstants.DustStatusMap.put(deviceVo.getStationId() , dustStatusVo) ;
                            handleEsdLog(deviceVo.getStationId() + "_1" , "失联" , "失联" ,deviceVo);
                        } else {
                            DeviceConstants.GatewayMissTimesMap.put(deviceVo.getServerIp() , 0);
                            String[] ss1 = tcpResult.split(" ");
                            String[] ss2 = tcpResult2.split(" ");
                            long data1 = NumberUtils.hexToLong(ss1[5] + ss1[6])* 65536L + NumberUtils.hexToLong(ss1[3]+ss1[4]); // 0.3um个数
                            long data2 = NumberUtils.hexToLong(ss1[9] + ss1[10])* 65536L + NumberUtils.hexToLong(ss1[7]+ss1[8]); // 0.5um个数
                            long data3 = NumberUtils.hexToLong(ss1[13] + ss1[14])* 65536L + NumberUtils.hexToLong(ss1[11]+ss1[12]); // 1.0um个数
                            long data4 = NumberUtils.hexToLong(ss1[17] + ss1[18])* 65536L + NumberUtils.hexToLong(ss1[15]+ss1[16]); // 2.5um个数
                            long data5 = NumberUtils.hexToLong(ss1[21] + ss1[22])* 65536L + NumberUtils.hexToLong(ss1[19]+ss1[20]); // 5.0um个数
                            long data6 = NumberUtils.hexToLong(ss1[25] + ss1[26])* 65536L + NumberUtils.hexToLong(ss1[23]+ss1[24]); // 10.0um个数

                            long max1 = NumberUtils.hexToLong(ss2[5] + ss2[6])* 65536L + NumberUtils.hexToLong(ss2[3]+ss2[4]); // 0.3um个数
                            long max2 = NumberUtils.hexToLong(ss2[9] + ss2[10])* 65536L + NumberUtils.hexToLong(ss2[7]+ss2[8]); // 0.5um个数
                            long max3 = NumberUtils.hexToLong(ss2[13] + ss2[14])* 65536L + NumberUtils.hexToLong(ss2[11]+ss2[12]); // 1.0um个数
                            long max4 = NumberUtils.hexToLong(ss2[17] + ss2[18])* 65536L + NumberUtils.hexToLong(ss2[15]+ss2[16]); // 2.5um个数
                            long max5 = NumberUtils.hexToLong(ss2[21] + ss2[22])* 65536L + NumberUtils.hexToLong(ss2[19]+ss2[20]); // 5.0um个数
                            long max6 = NumberUtils.hexToLong(ss2[25] + ss2[26])* 65536L + NumberUtils.hexToLong(ss2[23]+ss2[24]); // 10.0um个数

                            int level = NumberUtils.hexToInt(ss1[ss1.length-3]) ; // 洁净等级
                            boolean status1 = data1>= max1 ;
                            boolean status2 = data2>= max2 ;
                            boolean status3 = data3>= max3 ;
                            boolean status4 = data4>= max4 ;
                            boolean status5 = data5>= max5 ;
                            boolean status6 = data6>= max6 ;
                            PositionStoreVo positionStoreVo =
                                    DeviceConstants.ChannelStatusMap.get(deviceVo.getStationId() + "_1");
                            if (positionStoreVo == null) {
                                positionStoreVo = new PositionStoreVo() ;
                            }
                            positionStoreVo.setId(deviceVo.getStationId() + "_1");
                            if (status1 || status2 || status3 || status4 || status5 || status6){
                                positionStoreVo.setStatus("异常");
                                positionStoreVo.setDetail("CLASS " + level);
                            }else {
                                positionStoreVo.setStatus("正常");
                                positionStoreVo.setDetail("CLASS " + level);
                            }

                            positionStoreVo.setChannelTypeName(deviceChannels.get(0).getChannelType());
                            DeviceConstants.ChannelStatusMap.put(
                                    deviceVo.getStationId() + "_1",
                                    positionStoreVo);
                            DustStatusVo dustStatusVo = new DustStatusVo() ;
                            dustStatusVo.setPosition(deviceVo.getPosition());
                            dustStatusVo.setNum03(data1);
                            dustStatusVo.setNum05(data2);
                            dustStatusVo.setNum10(data3);
                            dustStatusVo.setNum25(data4);
                            dustStatusVo.setNum50(data5);
                            dustStatusVo.setNum100(data6);
                            dustStatusVo.setLevel(level+"");
                            if (level == 8){
                                dustStatusVo.setLevelDesc("十万级/CLASS");
                            }else if (level > 8){
                                dustStatusVo.setLevelDesc("百万级/CLASS");
                            }else{
                                dustStatusVo.setLevelDesc("<十万级/CLASS");
                            }
                            dustStatusVo.setStatus("通讯正常");
                            dustStatusVo.setStatus03(status1?"异常":"正常");
                            dustStatusVo.setStatus05(status2?"异常":"正常");
                            dustStatusVo.setStatus10(status3?"异常":"正常");
                            dustStatusVo.setStatus25(status4?"异常":"正常");
                            dustStatusVo.setStatus50(status5?"异常":"正常");
                            dustStatusVo.setStatus100(status6?"异常":"正常");
                            DeviceConstants.DustStatusMap.put(deviceVo.getStationId() , dustStatusVo) ;
                            if(status1 || status2 || status3 || status4 || status5 || status6){
                                handleEsdLog(deviceVo.getStationId() + "_" + 1,"异常","异常",deviceVo);
                            }else {
                                handleEsdLog(deviceVo.getStationId() + "_" + 1,"正常","正常",deviceVo);
                            }
                        }
                    }
                }
                else if(deviceVo.getDeviceTypeName().equals("温湿度测量仪")){
                    // TODO 原来的产品停产了，得重写
                }
                else if(deviceVo.getDeviceTypeName().startsWith("新版接地电阻仪")){
                    int timeout = 500 ;
                    int channelCount = deviceService.countChannels(deviceVo.getDeviceId());
                    String hexString = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()),8);
                    String commandStr = hexString + " 03 FF 11" ;
                    String resultStr = "";
                    ReentrantLock reentrantLock = DeviceConstants.LockMap.get(deviceVo.getServerIp());
                    reentrantLock.lock();
                    try {
                        resultStr = tcp_utils.sendCommand(deviceVo.getServerIp(), deviceVo.getServerPort(), commandStr, timeout );
                    } catch (Exception e) {
                        log.error("加锁失败！！ {}" , e.getMessage() );
                    } finally {
                        reentrantLock.unlock();
                    }
                    if (ResultUtils.checkResult(commandStr, resultStr)) {
                        DeviceConstants.GatewayMissTimesMap.put(deviceVo.getServerIp() , 0);
                        resultStr = resultStr.substring(15);
                        String[] ss = resultStr.split(" ");
                        int int1 = NumberUtils.hexToInt(ss[3] + ss[4]);
                        BigDecimal num1 = new BigDecimal(int1).divide(new BigDecimal(10)); // 通道1电阻值

                        int int2 = NumberUtils.hexToInt(ss[5] + ss[6]);
                        BigDecimal num2 = new BigDecimal(int2).divide(new BigDecimal(10)); // 通道2电阻值

                        int int3 = NumberUtils.hexToInt(ss[7] + ss[8]);
                        BigDecimal num3 = new BigDecimal(int3).divide(new BigDecimal(10)); // 通道3电阻值

                        int int4 = NumberUtils.hexToInt(ss[9] + ss[10]);
                        BigDecimal num4 = new BigDecimal(int4).divide(new BigDecimal(10)); // 通道4电阻值
                        String binary2 = NumberUtils.hexToBinary(ss[15], 8);
                        List<DeviceChannel> deviceChannels = deviceChannelService.getListByDeviceId(deviceVo.getDeviceId());
                        // 16 地线状态
                        if(ss[16].equals("01")) {
                            for (int i = 1; i <= channelCount; i++) {
                                PositionStoreVo positionStoreVo = getPositionStoreVo( deviceVo.getStationId(), i) ;
                                positionStoreVo.setId(deviceVo.getStationId() + "_" + i);
                                positionStoreVo.setStatus("异常");
                                positionStoreVo.setDetail("地线异常");
                                if(deviceChannels.size()>1){
                                    positionStoreVo.setChannelTypeName(deviceChannels.get(i-1).getChannelType());
                                }
                                DeviceConstants.ChannelStatusMap.put(deviceVo.getStationId() + "_" + i,
                                        positionStoreVo);
                                handleEsdLog(deviceVo.getStationId() + "_" + i , "异常" , "地线异常" ,deviceVo);
                            }
                        }else {

                            String flag1 = NumberUtils.hexToBinary(ss[11], 4);
                            String flag2 = NumberUtils.hexToBinary(ss[12], 4);
                            String flag3 = NumberUtils.hexToBinary(ss[13], 4);
                            String flag4 = NumberUtils.hexToBinary(ss[14], 4);

                            PositionStoreVo positionStoreVo = getPositionStoreVo( deviceVo.getStationId(), 1) ;
                            positionStoreVo.setId(deviceVo.getStationId() + "_" + 1);
                            positionStoreVo.setChannelTypeName(deviceChannels.get(0).getChannelType());
                            if (binary2.substring(6).equals("00")){
                                positionStoreVo.setStatus("正常");
                                String unit ;
                                if (deviceChannels.get(0).getChannelType().equals("设备接地")){
                                    unit = "Ω";
                                }else {
                                    unit = "MΩ";
                                }
                                positionStoreVo.setDetail(num1 + unit);
                                handleEsdLog(deviceVo.getStationId() + "_" + 1 , "正常" , "正常" ,deviceVo);
                            }else if (binary2.substring(6).equals("11")){
                                if (flag1.charAt(0)== '1'){
                                    positionStoreVo.setStatus("异常");
                                    positionStoreVo.setDetail("防呆");
                                    handleEsdLog(deviceVo.getStationId() + "_" + 1 , "异常" , "防呆" ,deviceVo);
                                }else {
                                    positionStoreVo.setStatus("待机");
                                    positionStoreVo.setDetail("手环待机");
                                    handleEsdLog(deviceVo.getStationId() + "_" + 1 , "待机" , "手环待机" ,deviceVo);
                                }
                            }else{
                                positionStoreVo.setStatus("异常");
                                positionStoreVo.setDetail("异常");
                                handleEsdLog(deviceVo.getStationId() + "_" + 1 , "异常" , "异常" ,deviceVo);
                            }
                            DeviceConstants.ChannelStatusMap.put(deviceVo.getStationId() + "_" + 1,
                                    positionStoreVo);

                            PositionStoreVo positionStoreVo2 = getPositionStoreVo( deviceVo.getStationId(), 2) ;
                            positionStoreVo2.setId(deviceVo.getStationId() + "_" + 2);
                            positionStoreVo2.setChannelTypeName(deviceChannels.get(1).getChannelType());
                            if (binary2.startsWith("00", 4)){
                                positionStoreVo2.setStatus("正常");
                                String unit ;
                                if (deviceChannels.get(1).getChannelType().equals("设备接地")){
                                    unit = "Ω";
                                }else {
                                    unit = "MΩ";
                                }
                                positionStoreVo2.setDetail(num2 + unit);
                                handleEsdLog(deviceVo.getStationId() + "_" + 2 , "正常" , "正常" ,deviceVo);
                            }else if (binary2.startsWith("11", 4)){
                                if (flag2.charAt(0)== '1'){
                                    positionStoreVo2.setStatus("异常");
                                    positionStoreVo2.setDetail("防呆");
                                    handleEsdLog(deviceVo.getStationId() + "_" + 2 , "异常" , "防呆" ,deviceVo);
                                }else {
                                    positionStoreVo2.setStatus("待机");
                                    positionStoreVo2.setDetail("手环待机");
                                    handleEsdLog(deviceVo.getStationId() + "_" + 2 , "待机" , "手环待机" ,deviceVo);
                                }
                            }else{
                                positionStoreVo2.setStatus("异常");
                                positionStoreVo2.setDetail("异常");
                                handleEsdLog(deviceVo.getStationId() + "_" + 2 , "异常" , "异常" ,deviceVo);
                            }
                            DeviceConstants.ChannelStatusMap.put(deviceVo.getStationId() + "_" + 2,
                                    positionStoreVo2);
                            if (deviceVo.getDeviceTypeName().equals("新版接地电阻仪（4通道）")){
                                PositionStoreVo positionStoreVo3 = getPositionStoreVo( deviceVo.getStationId(), 3) ;
                                positionStoreVo3.setId(deviceVo.getStationId() + "_" + 3);
                                positionStoreVo3.setChannelTypeName(deviceChannels.get(2).getChannelType());
                                if (binary2.startsWith("00", 2)){
                                    positionStoreVo3.setStatus("正常");
                                    String unit ;
                                    if (deviceChannels.get(2).getChannelType().equals("设备接地")){
                                        unit = "Ω";
                                    }else {
                                        unit = "MΩ";
                                    }
                                    positionStoreVo3.setDetail(num3 + unit);
                                    handleEsdLog(deviceVo.getStationId() + "_" + 3 , "正常" , "正常" ,deviceVo);
                                }else if (binary2.startsWith("11", 2)){
                                    if (flag3.charAt(0)== '1'){
                                        positionStoreVo3.setStatus("异常");
                                        positionStoreVo3.setDetail("防呆");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 3 , "异常" , "防呆" ,deviceVo);
                                    }else {
                                        positionStoreVo3.setStatus("待机");
                                        positionStoreVo3.setDetail("手环待机");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 3 , "待机" , "手环待机" ,deviceVo);
                                    }
                                }else{
                                    positionStoreVo3.setStatus("异常");
                                    positionStoreVo3.setDetail("异常");
                                    handleEsdLog(deviceVo.getStationId() + "_" + 3 , "异常" , "异常" ,deviceVo);
                                }
                                DeviceConstants.ChannelStatusMap.put(deviceVo.getStationId() + "_" + 3,
                                        positionStoreVo3);
                                PositionStoreVo positionStoreVo4 = getPositionStoreVo( deviceVo.getStationId(), 4) ;
                                positionStoreVo4.setId(deviceVo.getStationId() + "_" + 4);
                                positionStoreVo4.setChannelTypeName(deviceChannels.get(3).getChannelType());
                                if (binary2.startsWith("00")){
                                    positionStoreVo4.setStatus("正常");
                                    String unit ;
                                    if (deviceChannels.get(3).getChannelType().equals("设备接地")){
                                        unit = "Ω";
                                    }else {
                                        unit = "MΩ";
                                    }
                                    positionStoreVo4.setDetail(num4 + unit);
                                    handleEsdLog(deviceVo.getStationId() + "_" + 4 , "正常" , "正常" ,deviceVo);
                                }else if (binary2.startsWith("11")){
                                    if (flag4.charAt(0)== '1'){
                                        positionStoreVo4.setStatus("异常");
                                        positionStoreVo4.setDetail("防呆");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 4 , "异常" , "防呆" ,deviceVo);
                                    }else {
                                        positionStoreVo4.setStatus("待机");
                                        positionStoreVo4.setDetail("手环待机");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 4 , "待机" , "手环待机" ,deviceVo);
                                    }
                                }else{
                                    positionStoreVo4.setStatus("异常");
                                    positionStoreVo4.setDetail("异常");
                                    handleEsdLog(deviceVo.getStationId() + "_" + 4 , "异常" , "异常" ,deviceVo);
                                }
                                DeviceConstants.ChannelStatusMap.put(deviceVo.getStationId() + "_" + 4,
                                        positionStoreVo4);
                            }
                        }
                    }
                    else{
                        List<DeviceChannel> deviceChannels = deviceChannelService.getListByDeviceId(deviceVo.getDeviceId());
                        if (resultStr.equals("error") || resultStr.isEmpty()) {
                            if(resultStr.equals("error") ) {
                                if(DeviceConstants.GatewayMissTimesMap.containsKey(deviceVo.getServerIp())){
                                    Integer timeoutTime = DeviceConstants.GatewayMissTimesMap.get(deviceVo.getServerIp());
                                    if (timeoutTime != null && timeoutTime < 10){
                                        DeviceConstants.GatewayMissTimesMap.put(
                                                deviceVo.getServerIp() ,
                                                DeviceConstants.GatewayMissTimesMap.get(deviceVo.getServerIp()) + 1
                                        );
                                    }
                                }else {
                                    DeviceConstants.GatewayMissTimesMap.put(deviceVo.getServerIp() , 1);
                                }
                            }else {
                                DeviceConstants.GatewayMissTimesMap.put(deviceVo.getServerIp() , 0);
                            }
                        }
                        for (int i = 1; i <= channelCount; i++) {
                            PositionStoreVo positionStoreVo =
                                    DeviceConstants.ChannelStatusMap.get(deviceVo.getStationId() + "_" + i);
                            if (positionStoreVo == null) {
                                positionStoreVo = new PositionStoreVo() ;
                            }
                            positionStoreVo.setId(deviceVo.getStationId() + "_" + i);
                            positionStoreVo.setStatus("失联");
                            positionStoreVo.setDetail("失联");
                            if(deviceChannels.size()>1){
                                positionStoreVo.setChannelTypeName(deviceChannels.get(i-1).getChannelType());
                            }else if(deviceChannels.size() == 1) {
                                positionStoreVo.setChannelTypeName(deviceChannels.get(0).getChannelType());
                            }
                            DeviceConstants.ChannelStatusMap.put(
                                    deviceVo.getStationId() + "_" + i,
                                    positionStoreVo);
                            handleEsdLog(deviceVo.getStationId() + "_" + i , "失联" , "失联" ,deviceVo);
                        }
                    }
                }
                else {
                    String deviceTypeName = deviceVo.getDeviceTypeName();
                    int channelCount = deviceService.countChannels(deviceVo.getDeviceId());
                    String hexString = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()),8);
                    String commandStr = "" ;
                    if (deviceTypeName.equals("接地电阻仪（2通道）") || deviceTypeName.equals("接地电阻仪（3通道）")){
                        commandStr = hexString + " " + "03 11 00";
                    }else if (deviceTypeName.contains("离子风扇")){
                        commandStr = hexString + " " + "03 05 01";
                    }
                    String resultStr = "";
                    ReentrantLock reentrantLock = DeviceConstants.LockMap.get(deviceVo.getServerIp());
                    reentrantLock.lock();
                    try {
                        resultStr = tcp_utils.sendCommand(deviceVo.getServerIp(), deviceVo.getServerPort(), commandStr, 500);
                    } catch (Exception e) {
                        log.error("加锁失败！！ {}" , e.getMessage() );
                    } finally {
                        reentrantLock.unlock();
                    }
                    if (ResultUtils.checkResult(commandStr, resultStr)) {
                        DeviceConstants.GatewayMissTimesMap.put(deviceVo.getServerIp() , 0);
                        if (deviceTypeName.equals("旧版离子风扇")){
                            PositionStoreVo positionStoreVo = getPositionStoreVo( deviceVo.getStationId(), 1) ;
                            resultStr = resultStr.substring(15, 29);
                            // 先取前两位 获取终端状态
                            String statusStr = resultStr.substring(0, 2);
                            // 通信协议规定的，前两位保存终端状态，需要转化为二进制才能分析
                            statusStr = NumberUtils.hexToBinary(statusStr, 8);
                            // 风档
                            Integer windLevel = NumberUtils.binaryToInt(statusStr.substring(0, 3)) ;
                            // 高压报警状态
                            String highStatus = statusStr.charAt(5)=='0'? "未报警" : "高压报警";
                            // 风扇报警状态
                            String fanStatus = statusStr.charAt(6)=='0'? "未报警" : "风扇报警";
                            // 封窗异常
                            String windowOpen = statusStr.charAt(3) == '0' ? "未报警" : "封窗异常";
                            // 开关机
                            String powerStatus = statusStr.charAt(7)=='0'? "待机" : "开机";
                            positionStoreVo.setId(deviceVo.getStationId() + "_" + 1);
                            if (powerStatus.equals("待机")){
                                positionStoreVo.setStatus("待机");
                                positionStoreVo.setDetail("待机");
                            }else if(fanStatus.equals("风扇报警")){
                                positionStoreVo.setStatus("异常");
                                positionStoreVo.setDetail("风扇报警");
                            }else if(highStatus.equals("高压报警")){
                                positionStoreVo.setStatus("异常");
                                positionStoreVo.setDetail("高压报警");
                            } else if(windowOpen.equals("封窗异常")){
                                positionStoreVo.setStatus("异常");
                                positionStoreVo.setDetail("封窗异常");
                            }else {
                                positionStoreVo.setStatus("正常");
                                positionStoreVo.setDetail(windLevel + "档");
                            }
                            positionStoreVo.setChannelTypeName("离子风扇");
                            DeviceConstants.ChannelStatusMap.put(
                                    deviceVo.getStationId() + "_" + 1,
                                    positionStoreVo);
                            handleEsdLog(
                                    deviceVo.getStationId() + "_" + 1 ,
                                    positionStoreVo.getStatus() ,
                                    positionStoreVo.getDetail() ,
                                    deviceVo);
                        }
                        else if (deviceTypeName.equals("接地电阻仪（2通道）") || deviceTypeName.equals("接地电阻仪（3通道）")){
                            List<DeviceChannel> deviceChannels = deviceChannelService.getListByDeviceId(deviceVo.getDeviceId());
                            String s = resultStr.substring(36, 65);
                            String[] ss = s.split(" ");
                            if (ss[ss.length-2].equals("01")){
                                // 有异常的情况 地线异常
                                for (int i = 1; i <= channelCount; i++) {
                                    PositionStoreVo positionStoreVo = getPositionStoreVo( deviceVo.getStationId(), i) ;
                                    positionStoreVo.setId(deviceVo.getStationId() + "_" + i);
                                    positionStoreVo.setStatus("异常");
                                    positionStoreVo.setDetail("地线异常");
                                    if(deviceChannels.size()>1){
                                        positionStoreVo.setChannelTypeName(deviceChannels.get(i-1).getChannelType());
                                    }else if(deviceChannels.size() == 1) {
                                        positionStoreVo.setChannelTypeName(deviceChannels.get(0).getChannelType());
                                    }
                                    DeviceConstants.ChannelStatusMap.put(deviceVo.getStationId() + "_" + i,
                                            positionStoreVo);
                                    handleEsdLog(deviceVo.getStationId() + "_" + i , "异常" , "地线异常" ,deviceVo);
                                }
                            }
                            else {
                                String toBinary = NumberUtils.hexToBinary(ss[ss.length - 1], 8);
                                String c1 = toBinary.substring(0, 2);
                                String c2 = toBinary.substring(2, 4);
                                String c3 = toBinary.substring(4, 6);
                                PositionStoreVo positionStoreVo1 = getPositionStoreVo( deviceVo.getStationId(), 1) ;
                                positionStoreVo1.setId(deviceVo.getStationId() + "_" + 1);
                                positionStoreVo1.setChannelTypeName(deviceChannels.get(0).getChannelType());
                                if (c1.equals("01")) {
                                    if (
                                            deviceChannels.get(0).getChannelType().equals("ESD手环") // 类型为手环
                                    ){
                                        if(ss[ss.length - 4].equals("00")){
                                            positionStoreVo1.setStatus("待机");
                                            positionStoreVo1.setDetail("手环待机");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 1,"待机","手环待机",deviceVo);
                                        }else if (ss[ss.length - 4].equals("10")){
                                            positionStoreVo1.setStatus("异常");
                                            positionStoreVo1.setDetail("防呆");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 1,"异常","防呆",deviceVo);
                                        }else{
                                            positionStoreVo1.setStatus("异常");
                                            positionStoreVo1.setDetail("低于下限");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 1,"异常","低于下限",deviceVo);
                                        }
                                    }else {
                                        positionStoreVo1.setStatus("异常");
                                        positionStoreVo1.setDetail("低于下限");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 1,"异常","低于下限",deviceVo);
                                    }
                                } else if (c1.equals("10")) {
                                    if (
                                            deviceChannels.get(0).getChannelType().equals("ESD手环") // 类型为手环
                                    ){
                                        if(ss[ss.length - 4].equals("00")){
                                            positionStoreVo1.setStatus("待机");
                                            positionStoreVo1.setDetail("手环待机");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 1,"待机","手环待机",deviceVo);
                                        }else if (ss[ss.length - 4].equals("10")){
                                            positionStoreVo1.setStatus("异常");
                                            positionStoreVo1.setDetail("防呆");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 1,"异常","防呆",deviceVo);
                                        }else{
                                            positionStoreVo1.setStatus("异常");
                                            positionStoreVo1.setDetail("高于上限");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 1,"异常","高于上限",deviceVo);
                                        }
                                    }else {
                                        positionStoreVo1.setStatus("异常");
                                        positionStoreVo1.setDetail("高于上限");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 1,"异常","高于上限",deviceVo);
                                    }
                                } else {
                                    int num = NumberUtils.hexToInt(ss[0] + ss[1]);
                                    if (
                                            deviceChannels.get(0).getChannelType().equals("ESD手环") // 类型为手环
                                    ) {
                                        if(ss[ss.length - 4].equals("00")){
                                            positionStoreVo1.setStatus("待机");
                                            positionStoreVo1.setDetail("手环待机");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 1,"待机","手环待机",deviceVo);
                                        }else if (ss[ss.length - 4].equals("10")){
                                            positionStoreVo1.setStatus("异常");
                                            positionStoreVo1.setDetail("防呆");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 1,"待机","手环待机",deviceVo);
                                        }else{
                                            positionStoreVo1.setStatus("正常");
                                            String unit ;
                                            unit = "MΩ";
                                            positionStoreVo1.setDetail(new BigDecimal(num).divide(new BigDecimal(100)) + unit);
                                            handleEsdLog(deviceVo.getStationId() + "_" + 1,"正常","正常",deviceVo);
                                        }

                                    } else {
                                        positionStoreVo1.setStatus("正常");
                                        String unit ;
                                        if ("台垫接地".equals(deviceChannels.get(0).getChannelType())){
                                            unit = "MΩ";
                                        }else {
                                            unit = "Ω";
                                        }
                                        positionStoreVo1.setDetail(new BigDecimal(num).divide(new BigDecimal(100)) + unit);
                                        handleEsdLog(deviceVo.getStationId() + "_" + 1,"正常","正常",deviceVo);
                                    }
                                }
                                DeviceConstants.ChannelStatusMap.put(
                                        deviceVo.getStationId() + "_" + 1,
                                        positionStoreVo1
                                );
                                PositionStoreVo positionStoreVo2 = getPositionStoreVo( deviceVo.getStationId(), 2) ;
                                positionStoreVo2.setId(deviceVo.getStationId() + "_" + 2);
                                if(deviceChannels.size()>1){
                                    positionStoreVo2.setChannelTypeName(deviceChannels.get(1).getChannelType());
                                }else if(deviceChannels.size() == 1) {
                                    positionStoreVo2.setChannelTypeName(deviceChannels.get(0).getChannelType());
                                }
                                if (c2.equals("01")) {
                                    if (
                                            deviceChannels.get(1).getChannelType().equals("ESD手环")
                                    ){
                                        String tempStr ;
                                        if (deviceChannels.get(0).getChannelType().equals("ESD手环")){
                                            tempStr = ss[ss.length - 3] ;
                                        }else {
                                            tempStr = ss[ss.length - 4] ;
                                        }
                                        if(tempStr.equals("00")){
                                            positionStoreVo2.setStatus("待机");
                                            positionStoreVo2.setDetail("手环待机");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 2,"待机","手环待机",deviceVo);
                                        }else if (tempStr.equals("10")){
                                            positionStoreVo2.setStatus("异常");
                                            positionStoreVo2.setDetail("防呆");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 2,"异常","防呆",deviceVo);
                                        }else{
                                            positionStoreVo2.setStatus("异常");
                                            positionStoreVo2.setDetail("低于下限");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 2,"异常","低于下限",deviceVo);
                                        }
                                    } else {
                                        positionStoreVo2.setStatus("异常");
                                        positionStoreVo2.setDetail("低于下限");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 2,"异常","低于下限",deviceVo);
                                    }

                                } else if (c2.equals("10")) {
                                    if (
                                            deviceChannels.get(1).getChannelType().equals("ESD手环")
                                    ){
                                        String tempStr ;
                                        if (deviceChannels.get(0).getChannelType().equals("ESD手环")){
                                            tempStr = ss[ss.length - 3] ;
                                        }else {
                                            tempStr = ss[ss.length - 4] ;
                                        }
                                        if(tempStr.equals("00")){
                                            positionStoreVo2.setStatus("待机");
                                            positionStoreVo2.setDetail("手环待机");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 2,"待机","手环待机",deviceVo);
                                        }else if (tempStr.equals("10")){
                                            positionStoreVo2.setStatus("异常");
                                            positionStoreVo2.setDetail("防呆");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 2,"异常","防呆",deviceVo);
                                        }else{
                                            positionStoreVo2.setStatus("异常");
                                            positionStoreVo2.setDetail("高于上限");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 2,"异常","高于上限",deviceVo);
                                        }
                                    } else {
                                        positionStoreVo2.setStatus("异常");
                                        positionStoreVo2.setDetail("高于上限");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 2,"异常","高于上限",deviceVo);
                                    }
                                } else {
                                    int num = NumberUtils.hexToInt(ss[2] + ss[3]);
                                    if (
                                            deviceChannels.get(1).getChannelType().equals("ESD手环")
                                        // 无手环接入
                                    ) {
                                        String tempStr ;
                                        if (deviceChannels.get(0).getChannelType().equals("ESD手环")){
                                            tempStr = ss[ss.length - 3] ;
                                        }else {
                                            tempStr = ss[ss.length - 4] ;
                                        }
                                        if (tempStr.equals("00")){
                                            positionStoreVo2.setStatus("待机");
                                            positionStoreVo2.setDetail("手环待机");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 2,"待机","手环待机",deviceVo);
                                        }else if(tempStr.equals("10")){
                                            positionStoreVo2.setStatus("异常");
                                            positionStoreVo2.setDetail("防呆");
                                            handleEsdLog(deviceVo.getStationId() + "_" + 2,"异常","防呆",deviceVo);
                                        }else {
                                            positionStoreVo2.setStatus("正常");
                                            String unit ;
                                            unit = "MΩ";
                                            positionStoreVo2.setDetail(new BigDecimal(num).divide(new BigDecimal(100)) + unit);
                                            handleEsdLog(deviceVo.getStationId() + "_" + 2,"正常","正常",deviceVo);
                                        }

                                    }
                                    else {
                                        positionStoreVo2.setStatus("正常");
                                        String unit ;
                                        if ("台垫接地".equals(deviceChannels.get(0).getChannelType())){
                                            unit = "MΩ";
                                        }else {
                                            unit = "Ω";
                                        }
                                        positionStoreVo2.setDetail(new BigDecimal(num).divide(new BigDecimal(100)) + unit);
                                        handleEsdLog(deviceVo.getStationId() + "_" + 2,"正常","正常",deviceVo);
                                    }
                                }
                                DeviceConstants.ChannelStatusMap.put(
                                        deviceVo.getStationId() + "_" + 2,
                                        positionStoreVo2);
                                if (deviceTypeName.contains("3通道")) {
                                    PositionStoreVo positionStoreVo = getPositionStoreVo( deviceVo.getStationId(), 3) ;
                                    positionStoreVo.setId(deviceVo.getStationId() + "_" + 3);
                                    if(deviceChannels.size()>1){
                                        positionStoreVo.setChannelTypeName(deviceChannels.get(2).getChannelType());
                                    }else if(deviceChannels.size() == 1) {
                                        positionStoreVo.setChannelTypeName(deviceChannels.get(0).getChannelType());
                                    }
                                    if (c3.equals("01")) {
                                        positionStoreVo.setStatus("异常");
                                        positionStoreVo.setDetail("低于下限");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 3,"异常","低于下限",deviceVo);
                                    } else if (c3.equals("10")) {
                                        positionStoreVo.setId(deviceVo.getStationId() + "_" + 3);
                                        positionStoreVo.setStatus("异常");
                                        positionStoreVo.setDetail("高于上限");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 3,"异常","高于上限",deviceVo);
                                    } else {
                                        int num = NumberUtils.hexToInt(ss[4] + ss[5]);
                                        positionStoreVo.setId(deviceVo.getStationId() + "_" + 3);
                                        positionStoreVo.setStatus("正常");
                                        positionStoreVo.setDetail(new BigDecimal(num).divide(new BigDecimal(100)) + "Ω");
                                        handleEsdLog(deviceVo.getStationId() + "_" + 3,"正常","正常",deviceVo);
                                    }
                                    DeviceConstants.ChannelStatusMap.put(
                                            deviceVo.getStationId() + "_" + 3,
                                            positionStoreVo);
                                }
                            }
                        }
                        else if (deviceTypeName.equals("离子风扇")){
                            resultStr = resultStr.substring(15, 71);
                            // 先取前两位 获取终端状态
                            String [] ss = resultStr.split(" ");
                            String statusStr = ss[0];
                            // 通信协议规定的，前两位保存终端状态，需要转化为二进制才能分析
                            statusStr = NumberUtils.hexToBinary(statusStr, 8);
                            // 风档
                            Integer windLevel = NumberUtils.binaryToInt(statusStr.substring(0, 3)) ;
                            // 开关机
                            String powerStatus = statusStr.charAt(7)=='0'? "待机" : "开机";
                            // 风扇状态
                            String fanStatusStr = ss[1] ;
                            fanStatusStr = NumberUtils.hexToBinary(fanStatusStr, 8);
                            // 高压报警状态
                            String highStatusStr = ss[2];
                            highStatusStr = NumberUtils.hexToBinary(highStatusStr, 8);
                            // 封窗报警状态
                            String openWindowStatusStr = ss[3];
                            openWindowStatusStr = NumberUtils.hexToBinary(openWindowStatusStr, 8);
                            // 清扫报警状态
                            String cleanStatusStr = ss[4];
                            cleanStatusStr = NumberUtils.hexToBinary(cleanStatusStr, 8);

                            // 解析通道数据
                            for (int i = 1; i <= channelCount; i++) {
                                PositionStoreVo positionStoreVo =
                                        DeviceConstants.ChannelStatusMap.get(deviceVo.getStationId() + "_" + i);
                                if (positionStoreVo == null) {
                                    positionStoreVo = new PositionStoreVo() ;
                                }
                                String fanStatus = (fanStatusStr.charAt(fanStatusStr.length()-i)=='0'?"":"风扇异常" );
                                String highStatus = (highStatusStr.charAt(highStatusStr.length()-i)=='0'?"":"高压异常") ;
                                String openWindowStatus = (openWindowStatusStr.charAt(openWindowStatusStr.length()-i)=='1'?"":"封窗异常" );
                                String cleanStatus = (cleanStatusStr.charAt(cleanStatusStr.length()-i)=='0'?"":"清扫异常" );
                                // 解析每个通道的放电针电压
                                String powerNum = NumberUtils.hexToInt(ss[4+i]) * 100 + "V";
                                // 平衡电压
                                String balancePower = NumberUtils.hexToInt(ss[10 + i]) + "V";
                                positionStoreVo.setId(deviceVo.getStationId() + "_" + i);
                                positionStoreVo.setFdzPower(powerNum);
                                positionStoreVo.setBalancePower(balancePower);
                                if (!fanStatus.isEmpty()){
                                    positionStoreVo.setStatus("异常");
                                    positionStoreVo.setDetail(fanStatus);
                                } else if (!highStatus.isEmpty()) {
                                    positionStoreVo.setStatus("异常");
                                    positionStoreVo.setDetail(highStatus);
                                }else if (!openWindowStatus.isEmpty()) {
                                    positionStoreVo.setStatus("异常");
                                    positionStoreVo.setDetail(openWindowStatus);
                                }else if (!cleanStatus.isEmpty()) {
                                    positionStoreVo.setStatus("异常");
                                    positionStoreVo.setDetail(cleanStatus);
                                }else{
                                    if (powerStatus.equals("开机")){
                                        positionStoreVo.setStatus("正常");
                                        positionStoreVo.setDetail(windLevel+"档");
                                    }else{
                                        positionStoreVo.setStatus("待机");
                                        positionStoreVo.setDetail(powerStatus);
                                    }
                                }
                                handleEsdLog(
                                        deviceVo.getStationId() + "_" + i ,
                                        positionStoreVo.getStatus() ,
                                        positionStoreVo.getDetail() ,
                                        deviceVo
                                );
                                positionStoreVo.setChannelTypeName("离子风扇");
                                DeviceConstants.ChannelStatusMap.put(
                                        deviceVo.getStationId() + "_" + i,
                                        positionStoreVo);
                            }
                        }
                    }
                    else{
                        List<DeviceChannel> deviceChannels = deviceChannelService.getListByDeviceId(deviceVo.getDeviceId());
                        if (resultStr.equals("error") || resultStr.isEmpty()) {
                            if(resultStr.equals("error") ) {
                                if(DeviceConstants.GatewayMissTimesMap.containsKey(deviceVo.getServerIp())){
                                    Integer timeoutTime = DeviceConstants.GatewayMissTimesMap.get(deviceVo.getServerIp());
                                    if (timeoutTime != null && timeoutTime < 10){
                                        DeviceConstants.GatewayMissTimesMap.put(
                                                deviceVo.getServerIp() ,
                                                DeviceConstants.GatewayMissTimesMap.get(deviceVo.getServerIp()) + 1
                                        );
                                    }
                                }else {
                                    DeviceConstants.GatewayMissTimesMap.put(deviceVo.getServerIp() , 1);
                                }
                            }else {
                                DeviceConstants.GatewayMissTimesMap.put(deviceVo.getServerIp() , 0);
                            }
                        }
                        for (int i = 1; i <= channelCount; i++) {
                            PositionStoreVo positionStoreVo =
                                    DeviceConstants.ChannelStatusMap.get(deviceVo.getStationId() + "_" + i);
                            if (positionStoreVo == null) {
                                positionStoreVo = new PositionStoreVo() ;
                            }
                            positionStoreVo.setId(deviceVo.getStationId() + "_" + i);
                            positionStoreVo.setStatus("失联");
                            positionStoreVo.setDetail("失联");
                            if(deviceChannels.size()>1){
                                positionStoreVo.setChannelTypeName(deviceChannels.get(i-1).getChannelType());
                            }else if(deviceChannels.size() == 1) {
                                positionStoreVo.setChannelTypeName(deviceChannels.get(0).getChannelType());
                            }
                            DeviceConstants.ChannelStatusMap.put(
                                    deviceVo.getStationId() + "_" + i,
                                    positionStoreVo);
                            handleEsdLog(deviceVo.getStationId() + "_" + i , "失联" , "失联" ,deviceVo);
                        }
                    }
                }
            }
        }
    }

    private void handleEsdLog(String stationId , String status , String logDetails , DeviceVo deviceVo){
        List<DeviceChannel> deviceChannels = deviceChannelService.getListByDeviceId(deviceVo.getDeviceId());
        String channelName;
        boolean enabled ;
        if (deviceChannels.size() == 1){
            channelName = deviceChannels.get(0).getChannelType();
            enabled = deviceChannels.get(0).getEnabled();
        }else {
            String[] ss = stationId.split("_");
            int i = Integer.parseInt(ss[1]);
            channelName = deviceChannels.get(i-1).getChannelType();
            enabled = deviceChannels.get(i-1).getEnabled();
        }
        EsdLog esdLog = esdLogService.getLatestLogByCreateTime(stationId);
        Boolean isView = deviceService.getViewOn(deviceVo.getStationId());
        if (esdLog == null){
            esdLog = new EsdLog();
            esdLog.setDeviceId(deviceVo.getDeviceId());
            esdLog.setStationId(stationId);
            esdLog.setStatusDesc(logDetails);
            esdLog.setDeviceTypeName(deviceVo.getDeviceTypeName());
            esdLog.setChannelName(channelName);
            esdLog.setLine(deviceVo.getLine());
            esdLog.setLineAndPosition(deviceVo.getLine()+ "-" + deviceVo.getPosition());
            esdLog.setStatus(status);
            esdLog.setEnabled(enabled);
            esdLog.setStartTime(LocalDateTime.now());
            esdLogService.save(esdLog);
        }else{
            esdLog.setEnabled(enabled);
            esdLog.setLine(deviceVo.getLine());
            esdLog.setDeviceId(deviceVo.getDeviceId());

            if (!isView){
                esdLog.setEndTime(LocalDateTime.now());
                esdLogService.updateById(esdLog);
                return ;
            }

            if(!logDetails.equals(esdLog.getStatusDesc()) || esdLog.getEndTime() != null){
                if (esdLog.getEndTime() == null ){
                    esdLog.setEndTime(LocalDateTime.now());
                    esdLog.setDeviceId(deviceVo.getDeviceId());
                    esdLogService.updateById(esdLog);
                }
                EsdLog esdLog1 = new EsdLog();
                esdLog1.setStationId(stationId);
                esdLog1.setDeviceId(deviceVo.getDeviceId());
                esdLog1.setStatusDesc(logDetails);
                esdLog1.setDeviceTypeName(deviceVo.getDeviceTypeName());
                esdLog1.setChannelName(channelName);
                esdLog1.setLine(deviceVo.getLine());
                esdLog1.setLineAndPosition(deviceVo.getLine()+ "-" + deviceVo.getPosition());
                esdLog1.setStatus(status);
                esdLog1.setEnabled(enabled);
                esdLog1.setStartTime(LocalDateTime.now());
                esdLogService.save(esdLog1);
            }else {
                esdLogService.updateById(esdLog);
            }
        }
    }

    private PositionStoreVo getPositionStoreVo(String stationId, int channel){
        PositionStoreVo positionStoreVo =
                DeviceConstants.ChannelStatusMap.get(stationId + "_" + channel);
        if (positionStoreVo == null) {
            return new PositionStoreVo() ;
        }else {
            return positionStoreVo;
        }
    }
}
